import { ChangeDetectionStrategy, Component } from '@angular/core';
import { type ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { BrnAvatar } from './brn-avatar';
import { BrnAvatarFallback } from './fallback/brn-avatar-fallback';
import { BrnAvatarImage } from './image/brn-avatar-image';

@Component({
	selector: 'brn-mock',
	imports: [BrnAvatarImage, BrnAvatarFallback, BrnAvatar],
	changeDetection: ChangeDetectionStrategy.OnPush,
	template: `
		<brn-avatar id="empty">
			<p>empty</p>
		</brn-avatar>
		<brn-avatar id="fallbackOnly">
			<span brnAvatarFallback>fallback</span>
		</brn-avatar>
		<brn-avatar id="noSrc">
			<img brnAvatarImage alt="Avatar image" />
			<span brnAvatarFallback>fallback</span>
		</brn-avatar>
		<brn-avatar id="good">
			<img
				brnAvatarImage
				alt="Avatar image"
				src=""
			/>
			<span brnAvatarFallback>fallback</span>
		</brn-avatar>
	`,
})
class Mock {}

describe('BrnAvatarComponent', () => {
	let component: Mock;
	let fixture: ComponentFixture<Mock>;

	beforeEach(() => {
		fixture = TestBed.createComponent(Mock);
		component = fixture.componentInstance;
		fixture.autoDetectChanges();
	});
	it('should compile', () => {
		expect(component).toBeTruthy();
	});

	it('should render the fallback when no image is provided', () => {
		const fallback = fixture.nativeElement.querySelector('#fallbackOnly span');
		expect(fallback.textContent).toEqual('fallback');
	});

	it('should not render anything when no image or fallback is provided', () => {
		const empty = fixture.nativeElement.querySelector('#empty p');
		expect(empty).toBeFalsy();
	});

	it('should render the fallback when provided and image with no src', () => {
		const fallback = fixture.nativeElement.querySelector('#noSrc span');
		expect(fallback.textContent).toEqual('fallback');
	});

	it('should not render the fallback, but rather the image when provided with a valid src', () => {
		// delay test to allow for image to resolve
		setTimeout(() => {
			const img = fixture.debugElement.query(By.css('#good img'));
			expect(img).toBeTruthy();
			const fallback = fixture.nativeElement.querySelector('#good span');
			expect(fallback).toBeFalsy();
		});
	});
});
